/**
 * Filename: TodayShareActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/6/29 2:57
 */
package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopListAlbum;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 今日忆分享页
 */
public class TodayShareActivity extends BaseActivity implements PopListAlbum.OnImageAlbumSelected, View.OnClickListener {
    private Toolbar mToolbar;
    private ImageView btn_share_local;
    private ImageView btn_share_yinian;
    private ImageView btn_share_wx_timeline;
    private ImageView btn_share_wx_friend;
    private ImageView btn_share_qq_timeline;
    private ImageView btn_share_qq;
    private String shareStr;
    private View view;
    private String curGroup;
    private List<YNAlbum> mDatas;
    private String nameStr;
    private UMShareAPI mShareAPI;
    private PopListAlbum mPopListAlbumPopupWindow;        // 弹窗相册路径
    private int mScreenHeight;                    // 屏高
    Handler downloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    SnackBarUtils.makeShort(mToolbar, "保存成功！").show();
                    break;
                case 1:
                    SnackBarUtils.makeShort(mToolbar, "网络连接失败！").show();
                    break;
                case 0:
                    SnackBarUtils.makeShort(mToolbar, "保存失败！").show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_today_share);
        shareStr = getIntent().getStringExtra(ACTIONs.aAddData);
        mDatas = YNSingleton.getInstance().getAlbumList();
        mScreenHeight = DisplayUtils.getScreenHeightPixels(this);
        mShareAPI = UMShareAPI.get(this);
        initView();
        initListAlbumPopupWindw();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.today_share_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        view = findViewById(R.id.root_today_share);
        btn_share_local = (ImageView) findViewById(R.id.btn_share_local);
        btn_share_yinian = (ImageView) findViewById(R.id.btn_share_yinian);
        btn_share_wx_timeline = (ImageView) findViewById(R.id.btn_share_wx_timeline);
        btn_share_wx_friend = (ImageView) findViewById(R.id.btn_share_wx_friend);
        btn_share_qq_timeline = (ImageView) findViewById(R.id.btn_share_qq_timeline);
        btn_share_qq = (ImageView) findViewById(R.id.btn_share_qq);
        btn_share_local.setOnClickListener(this);
        btn_share_yinian.setOnClickListener(this);
        btn_share_wx_timeline.setOnClickListener(this);
        btn_share_wx_friend.setOnClickListener(this);
        btn_share_qq_timeline.setOnClickListener(this);
        btn_share_qq.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 保存至本地
            case R.id.btn_share_local:
                Long tsLong = System.currentTimeMillis() / 1000;
                String ts = "yn_" + tsLong.toString() + ".png";
                SnackBarUtils.makeShort(mToolbar, "正在下载...").show();
                downPic(shareStr, ts);
                break;
            // 保存到忆年相册
            case R.id.btn_share_yinian:
                chooseGroup();
                Intent statintentyinian = new Intent(ACTIONs.record);
                statintentyinian.putExtra("key", "todayMemoryYinian_6");
                statintentyinian.putExtra("value", 1);
                sendBroadcast(statintentyinian);
                break;
            // 朋友圈
            case R.id.btn_share_wx_timeline:
                Log.d("yuhao", "shareStr=" + shareStr);
                new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                        .withMedia(new UMImage(this, shareStr + "?imageView2/2/w/400"))
                        .share();
                Intent statintent = new Intent(ACTIONs.record);
                statintent.putExtra("key", "todayMemoryFriendCircle_6");
                statintent.putExtra("value", 1);
                sendBroadcast(statintent);
                break;
            // 微信好友
            case R.id.btn_share_wx_friend:
                UMImage image = new UMImage(this, shareStr + "?imageView2/2/w/400");
                UMImage thumb = new UMImage(this, shareStr + "?imageView2/2/w/30");
                image.setThumb(thumb);
                new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                        .withText("今日忆")
                        .withMedia(image)
                        .share();
                Intent statintentfriend = new Intent(ACTIONs.record);
                statintentfriend.putExtra("key", "todayMemoryWechat_6");
                statintentfriend.putExtra("value", 1);
                sendBroadcast(statintentfriend);
                break;
            // qq空间
            case R.id.btn_share_qq_timeline:
                UMImage imagezone = new UMImage(this, shareStr + "?imageView2/2/w/400");
                UMImage thumbzone = new UMImage(this, shareStr + "?imageView2/2/w/30");
                imagezone.setThumb(thumbzone);
                new ShareAction(this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                        .withText("今日忆")
                        .withMedia(imagezone)
                        .share();
                Intent statintentzone = new Intent(ACTIONs.record);
                statintentzone.putExtra("key", "todayMemoryQZone_6");
                statintentzone.putExtra("value", 1);
                sendBroadcast(statintentzone);
                break;
            case R.id.btn_share_qq:
                UMImage imageqq = new UMImage(this, shareStr + "?imageView2/2/w/400");
                UMImage thumbqq = new UMImage(this, shareStr + "?imageView2/2/w/30");
                imageqq.setThumb(thumbqq);
                new ShareAction(this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                        .withText("今日忆")
                        .withMedia(imageqq)
                        .share();
                Intent statintentqq = new Intent(ACTIONs.record);
                statintentqq.putExtra("key", "todayMemoryQQ_6");
                statintentqq.putExtra("value", 1);
                sendBroadcast(statintentqq);
                break;
        }
    }

    private void downPic(final String url, final String name) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        new Thread(new Runnable() {
            public void run() {
                try {
                    URL url1 = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        File f = new File(new File(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/", "yinian/YiNian" + name);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                        downloadHandler.sendEmptyMessage(2);
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(f);
                        intent.setData(uri);
                        sendBroadcast(intent);
                    } else {
                        downloadHandler.sendEmptyMessage(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    downloadHandler.sendEmptyMessage(0);
                }
            }
        }).start();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(TodayShareActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TodayShareActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(TodayShareActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(TodayShareActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private void chooseGroup() {
        if (shareStr.length() <= 0) return;
        nameStr = shareStr.substring(shareStr.lastIndexOf("/") + 1);
        if (mDatas.size() <= 0) {
            showToast("请先创建圈子再发布");
            return;
        }
        mPopListAlbumPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = .8f;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    // 选择发布相册的弹框初始化
    private void initListAlbumPopupWindw() {
        mPopListAlbumPopupWindow = new PopListAlbum(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.5),
                mDatas, LayoutInflater.from(this)
                .inflate(R.layout.yn_album_list_dir, null));
        mPopListAlbumPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 设置背景颜色
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        mPopListAlbumPopupWindow.setOnImageAlbumSelected(this);
    }

    // 选择相册回调
    @Override
    public void selected(YNAlbum item) {
        curGroup = String.valueOf(item.getGroupid());
        doUpPic();
        mPopListAlbumPopupWindow.dismiss();
    }


    private String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    private void doUpPic() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, curGroup);
        mParam.put(CommonConstants.YNS_CONTENT, " ");
        mParam.put(CommonConstants.YNS_PIC_ADDRESS, CommonConstants.YNQNURL + nameStr);
        mParam.put(CommonConstants.YNS_PIC_MODE, "private");
        mParam.put(CommonConstants.YNS_MEMORYTIME, getCurrentTime());
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynUploadEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resStatus = gson.fromJson(s, YNStatusResponse.class);
                        if (ReqUtils.isSuccess(resStatus.getCode())) {
                            showToast("发布成功");
                            finish();
                        } else {
                            showToast(resStatus.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    // 友盟统计
    public void onResume() {
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
